package util

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 表单 POST 请求
func fetchFormData[T any](requestUrl string, m map[string]string, ctx context.Context) ([]T, error) {
	// 准备表单数据
	formData := url.Values{}
	for key, value := range m {
		formData.Set(key, value)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, "POST", requestUrl, strings.NewReader(formData.Encode()))
	//json请求 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}

	// 设置表单请求头
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	// 设置 JSON 头	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("X-Request-ID", fmt.Sprintf("req_%d", time.Now().Unix()))

	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 检查状态码
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("API 返回错误状态码: %d", resp.StatusCode)
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %w", err)
	}

	// 解析 JSON
	var t []T
	err = json.Unmarshal(body, &t)
	if err != nil {
		return nil, fmt.Errorf("JSON 解析失败: %w", err)
	}

	fmt.Printf("从 API 获取到 %d 条用户数据\n", len(t))
	return t, nil
}

func fetchFromAPI[T any](url string) ([]T, error) {
	// 创建请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %w", err)
	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "MyApp/1.0")

	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 30 * time.Second,
	}
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查状态码
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("API 返回错误状态码: %d", resp.StatusCode)
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %w", err)
	}

	// 解析 JSON
	var t []T
	err = json.Unmarshal(body, &t)
	if err != nil {
		return nil, fmt.Errorf("JSON 解析失败: %w", err)
	}

	fmt.Printf("从 API 获取到 %d 条用户数据\n", len(t))
	return t, nil
}
